#include "clog.h"
#include <QTime>
#include <QReadWriteLock>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include "serversetting.h"
#include "locol_ips/clocolips.h"

static CLog *_log = NULL;
static bool _resetFile = false;

CLog::CLog(QObject *parent) :
    QObject(parent)
{
    _logFile = new QFile("./Record");
    if(!_logFile->open(QFile::ReadWrite))
    {
        printf("Open log file error \n");
    }

    connect(this,SIGNAL(s_log(QString)),this,SLOT(doWriteLog(QString)));
    connect(&timer,SIGNAL(timeout()),this,SLOT(doFileSizeCheck()));
    timer.start(1000);

    _httpRecord = new CHttpManger(this);
    connect(_httpRecord,SIGNAL(s_reply(QByteArray)),this,SLOT(doRecordUpdateResult(QByteArray)));

    _httpRS = new CHttpManger(this);
    connect(_httpRS,SIGNAL(s_reply(QByteArray)),this,SLOT(doRecordStateResult(QByteArray)));

    //doRecordStateResult("{\"state\":1,\"success\":true}");

    requestRecordState();
}

void CLog::doFileSizeCheck()
{
    if(_upList.size()>0)
        _cacheLog = _upList.takeFirst();

    while(_upList.size()>0)
    {
        if(_cacheLog.size()>2048)
        {
           break;
        }
        else
        {
            _cacheLog += ";" + _upList.takeFirst();
        }
    }

    int r = doRecordUpdate(_cacheLog);
    if(r != 0)
    {
        r = doRecordUpdate(_cacheLog);
        if(r!=0)
        {
            r = doRecordUpdate(_cacheLog);
        }

        if(r!=0)
        {
            debugOutput(_cacheLog);
        }
    }

    _cacheLog.clear();

}

CLog * CLog::getSingle()
{
    if(_log == NULL)
    {
        _log = new CLog();
    }

    return _log;
}

void CLog::debugOutput(const QString &msg)
{
    if(_logFile->isOpen())
    {
        _logFile->write(msg.toLatin1());
        _logFile->flush();

        if(_logFile->size() > 100*1024*1024)
        {
            QFile::remove("./Record.bak");
            _logFile->copy("./Record.bak");
            _logFile->seek(0);
            _logFile->resize(0);
        }
    }
}

void CLog::logOutput(QString msg)
{
    QString str = QString("%1 - %2\n").arg(QDateTime::currentDateTime().toString()).arg(msg);
    emit s_log(str);
}

void CLog::doWriteLog(QString msg)
{
    _upList.append(msg);
}

int CLog::doRecordUpdate(QString d)
{
    if(d.isEmpty())
        return -1;

    QString reqUrl = ServerSetting::defaultSetting()->_record_url;
//    // http://192.168.1.137:8080/TTG_ic/rest/jsonServices/showAll?projectId=1

    QString req = QString("serial=%1&sts=%2")
            .arg(ServerSetting::defaultSetting()->_serial)
            .arg(d);

    _httpRecord->httpPostSend(reqUrl,req.toUtf8());

    //qDebug() << "Record Update:" << req;
}

void CLog::requestRecordState()
{
    CLocolIPS::gSendRecord = ServerSetting::defaultSetting()->_record == 1 ? true:false;
    //http request

    QString reqUrl = ServerSetting::defaultSetting()->_rstate_url;
    //    // http://192.168.1.137:8080/TTG_ic/rest/jsonServices/showAll?projectId=1

    QString req = QString("serial=%1")
                .arg(ServerSetting::defaultSetting()->_serial);


    _httpRS->httpPostSend(reqUrl,req.toUtf8());

    qDebug() << "Get Record Status:" << req;

}

void CLog::doRecordUpdateResult(QByteArray ret)
{
    //qDebug() << "RecordUpdateResult:" << ret;
}

void CLog::doRecordStateResult(QByteArray ret)
{
    QJsonDocument domTree = QJsonDocument::fromJson(ret);

    if (domTree.isNull() || domTree.isEmpty())
    {
        qDebug() << "Json 格式错误 RecordStateResult : " << ret;
        return ;
    }

    qDebug() << "doRecordStateResult:" << ret;

    if(domTree.isObject())
    {
        QJsonObject jobj = domTree.object();
        QString cmdStr = "";

        QJsonObject::Iterator it = jobj.begin();
        while (it != jobj.end()) {

            cmdStr = it.key();
            if(cmdStr == "state")
            {
                int rs = it.value().toInt();
                CLocolIPS::gSendRecord = rs == 1?true:false;
                break;
            }

            it++;
        }
    }
}
